/*
全局配置 base url
 */

import axios from 'axios'
import store from './store'
import Vue from 'vue'
import router from './router'

// 基础配置
axios.defaults.timeout = 5000;  // 超时时间
axios.defaults.baseURL = 'http://127.0.0.1:5000/api';

//自动帮你添加 Token 到请求头 Authorization 中，不需要手动添加 token
axios.interceptors.request.use(function (config) {
  const token = window.localStorage.getItem('madblog-token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, function (error) {
  return Promise.reject(error)

});

// 自动处理 jwt 过期后的错误：401 UNAUTHORIZED
axios.interceptors.response.use(function (response) {
  // Do something with response data
  return response
}, function (error) {
  // Do something with response error
  switch (error.response.status) {
    case 401:
      // 清除 Token 及 已认证 等状态
      store.logoutAction();
      // 跳转到登录页
      if (router.currentRoute.path !== '/login') {
        Vue.toasted.error('401: 认证已失效，请先登录', {icon: 'fingerprint'})
        router.replace({
          path: '/login',
          query: {redirect: router.currentRoute.path},
        })
      }
      break

    case 404:
      Vue.toasted.error('404: NOT FOUND', {icon: 'fingerprint'})
      router.back()
      break
  }
  return Promise.reject(error)
});

export default axios
